package com.chinacreator.galaxylive.service;

import com.chinacreator.c2.config.ConfigManager;
import com.chinacreator.galaxylive.bean.UserBean;
import com.chinacreator.galaxylive.exception.OutHttpRestException;
import com.chinacreator.galaxylive.utils.RestEampClient;
import com.chinacreator.galaxylive.utils.SessionUtils;
import com.chinacreator.galaxylive.utils.ToolUtil;
import com.chinacreator.galaxylive.wx.WxService;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.MultiValueMap;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Service
public class PageService {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private WxService wxService;

    @Autowired
    private HttpServletRequest request;

    /**
     * 记录微信用户，并入库
     * @param wxUser
     * @return
     */
    public UserBean insertWxUser(WxMpUser wxUser){
        UserBean userBean = null;
        UserBean ub = new UserBean();
        ub.setUniqueId(wxUser.getOpenId());
        ub.setName(wxUser.getNickname());
        ub.setProvince(wxUser.getProvince());
        ub.setAvatar(wxUser.getHeadImgUrl());
        ub.setCity(wxUser.getCity());
        ub.setAppId(ConfigManager.getInstance().getConfig("wx_appid"));
        if(wxUser.getSubscribe() != null){
            ub.setIsSubscribe(wxUser.getSubscribe() ? "1" : "0");
        }
        MultiValueMap<String, String> headers = new HttpHeaders();
        headers.add("Content-Type","application/json;charset=UTF-8");
        ResponseEntity<String> responseEntity = RestEampClient.createRestEampClient()
                .url(ConfigManager.getInstance().getConfig("live.serviceInterfaceUrl") + "/galaxy/v1/user/wx/", null)
                .header(headers)
                .post(ub, String.class);
        if (responseEntity.getStatusCode().equals(HttpStatus.OK)) {
            userBean = ToolUtil.jsonToObject(responseEntity.getBody(),UserBean.class);
        } else if (!responseEntity.getStatusCode().equals(HttpStatus.NO_CONTENT)) {
            throw new OutHttpRestException(responseEntity);
        }
        return userBean;
    }

    /**
     * 校验机构是否正确
     * @param n
     * @return
     */
    public boolean checkOrg(String n) {
        SessionUtils.setCurrentOrgId(request,n);
        return true;
    }

    /**
     * 获取用户信息
     * @return
     */
    public UserBean getUserBean() {
        UserBean userBean = SessionUtils.getSessionUser(request);
        if(userBean == null){
            WxMpUser wxMpUser = wxService.getWxMpUser(request);
            if(wxMpUser != null){
                userBean = this.getUserBean(wxMpUser.getOpenId());
                if(userBean == null){
                    userBean = insertWxUser(wxMpUser);
                }else{
                	if(!userBean.getAvatar().equals(wxMpUser.getHeadImgUrl()) 
                			|| !userBean.getName().equals(wxMpUser.getNickname())){
                		userBean = insertWxUser(wxMpUser);
                	}
                }
                SessionUtils.setUser(request,userBean);
            }else {
                //TODO 获取用户信息失败
            }
        }
        return userBean;
    }


    private UserBean getUserBean(String openId){
        ResponseEntity<String> responseEntity = RestEampClient.createRestEampClient()
                .url(ConfigManager.getInstance().getConfig("live.serviceInterfaceUrl")+"/galaxy/v1/user/wx/{openId}",null,openId)
                .get(String.class);
        if(responseEntity.getStatusCode().equals(HttpStatus.OK)){
            return ToolUtil.jsonToObject(responseEntity.getBody(),UserBean.class);
        }else if(responseEntity.getStatusCode().equals(HttpStatus.NO_CONTENT)){
            return null;
        }else {
            throw new OutHttpRestException(responseEntity);
        }
    }


}
